import requests
import os
import json
import random
import time
import typing
from conf import Conf



class DataSource:
  
  # 获取json数据,如果本地不存在则发送请求
  @staticmethod
  def __get_data_json( url :str, outputName :str) -> dict:
    if not os.path.exists("json"):
      os.mkdir("json")
    if not os.path.exists("./json/"+outputName):
      res = requests.get(url)
      with open("./json/"+outputName, "w", encoding="utf8") as f:
        f.write(res.text)
      return res.json()
    else:
      with open("./json/"+outputName, "r",encoding="utf8") as f:
        return json.loads(f.read())

  @staticmethod
  def get_city_json() -> dict:
    return DataSource.__get_data_json(
      "https://www.zhipin.com/wapi/zpCommon/data/cityGroup.json", 
      "city.json"
    )
   
  @staticmethod 
  def get_industry_json():
    return DataSource.__get_data_json(
      "https://www.zhipin.com/wapi/zpCommon/data/industryFilterExemption",
      "industry.json"
    )    
    
  @staticmethod
  def get_position_json():
    return DataSource.__get_data_json(
      "https://www.zhipin.com/wapi/zpCommon/data/getCityShowPosition",
      "position.json"
    )
    
  # 传递城市的list, 元素是(代码, 城市名)
  @staticmethod
  def get_cities() -> list[tuple[int, str]]:
    data = DataSource.get_city_json()
    filtered = Conf.getConf()["include"]["cities"].split(",")
    groups :list[dict] = data["zpData"]["cityGroup"]
    cityLists :list[list[dict]] = list(map(lambda d:d["cityList"], groups))
    cities = []
    filtered = Conf.getConf()["include"]["cities"].split(",")

    for cityList in cityLists:
      for city in cityList:
        if not (filtered == ["*"]  or city["name"] in filtered):
          continue
        cities.append((city["code"], city["name"]))  
    return cities


  @staticmethod
  def get_industries()-> list[tuple[int, str]]:
    cond = lambda d: True if d["name"] == "互联网/AI" or d["name"] == "电子/通信/半导体" else False
    data :list[dict] = list(filter(cond, DataSource.get_industry_json()["zpData"]))
    industries = []
    filtered = Conf.getConf()["include"]["industries"].split(",")
    for modelList in data:
      for model in modelList["subLevelModelList"]:
        if not (filtered == ["*"]  or model["name"] in filtered):
          continue
        industries.append((model["code"], model["name"]))
    return industries



  @staticmethod
  def get_positions()->list[tuple]:
    data :list[dict] = DataSource.get_position_json()["zpData"]["position"]
    cond = lambda d: True if d["name"] == "互联网/AI" or d["name"] == "电子/电气/通信" else False
    data = list(filter(cond, data))
    positions = []
    filtered = Conf.getConf()["include"]["positionTypes"].split(",")
    for positionList in data:
      for positionType in positionList["subLevelModelList"]:
        if not (filtered == ["*"] or positionType["name"] in filtered):
          continue
        for position in positionType["subLevelModelList"]:
          positions.append((positionType["code"],positionType["name"], position["code"], position["name"]))
    return positions
  
  

  # 返回热门城市, 领域, 岗位的名称和代码
  @staticmethod
  def get_indices()->dict[str,list[tuple]]:

      cities = DataSource.get_cities()

      industries = DataSource.get_industries()
      positions = DataSource.get_positions()
      data = {
        "cities":cities,
        "industries":industries,
        "positions":positions
      }
    
      return data


